<template>
  <top-navbar title="确认订单" />
  <div class="comfirmOrder min-h-screen from-hex-FFFFFF to-hex-F5F5F5 bg-gradient-to-b px-32rpx">
    <!-- <div class="z-999 flex items-center pb-40rpx"
         :style="{ paddingTop: `${searchBarTop}px` }"
         @click.stop="goback">
      <uni-icons type="back" size="28" />
      <text class="text-36rpx font-600">确认订单</text>
    </div> -->
    <div
      class="mb-44rpx mt-38rpx box-border flex items-center justify-between pl-4rpx"
      @click="navTo('/pages-shop/deliveryWay?isUpdateAddress=0')">
      <div>
        <div class="mb-18rpx flex items-center">
          <text v-if="userInfoDo"
                class="text-28rpx font-600 text-hex-333333">{{ userInfoDo.name }} {{ userInfoDo.mobile }}</text>
        </div>
        <div v-if="userInfoDo" class="flex items-center text-24rpx text-hex-5A736A">
          <image
            :src="`${cdnUrl}/svgicons/tea/position.svg${imgVersion}`"
            mode="scaleToFill"
            class="h-50rpx w-50rpx -ml-10rpx"
          />
          <div class="w-80%">{{ userInfoDo.address }} {{ userInfoDo.detail }}</div>
        </div>
      </div>
      <div class="flex items-center">
        <image
          :src="`${cdnUrl}/svgicons/home/more.svg${imgVersion}`"
          mode="scaleToFill"
          class="h-32rpx w-32rpx"
        />
      </div>
    </div>
    <div class="mb-32rpx box-border rounded-32rpx bg-hex-F6F6F6">
      <div v-for="item in realGoodsList" class="mb-32rpx rounded-24rpx bg-hex-fff p-24rpx">
        <div v-if="item.isHasActive" class="mb-18rpx flex">
          <div class="mr-8rpx border-2rpx border-hex-FF4E4E rounded-8rpx border-solid px-8rpx py-4rpx text-20rpx text-hex-FF4E4E">{{ handlegetactive(item.active) }}</div>
          <div class="text-24rpx text-hex-67686F">{{ item.activeName }}</div>
        </div>
        <div
          class="mb-32rpx box-border flex justify-between"
        >
          <div class="w-90% flex">
            <div 
              class="relative mr-3% mt-24rpx h-180rpx w-180rpx overflow-hidden rounded-16rpx">
              <image
                class="absolute left-50% top-50% h-180rpx w-180rpx rounded-16rpx"
                style="transform: translate(-50%, -50%);" :src="item.productImage" mode="aspectFill" />
            </div>
            <div class="w-70% flex flex-col justify-between">
              <div class="text-28rpx font-600 text-hex-333333">{{ item.productName }}</div>
              <div class="flex items-center text-24rpx text-hex-7C8699">
                <div>{{ item.specs }}</div>
              </div>
            </div>
          </div>
          <div class="w-10% flex flex-col justify-between">
            <div>
              <div class="mb-4rpx text-28rpx text-hex-333333">¥{{ item.promotePrice }}</div>
              <div class="text-24rpx text-hex-999999 line-through">¥{{ item.price }}</div>
            </div>
            <div class="text-24rpx text-hex-999999">x{{ item.amount }}</div>
          </div>
        </div>
        <div v-if="item.isHasActive">
          <div
            v-for="itm in item.childList"
            class="box-border flex justify-between"
          >
            <div class="w-90% flex">
              <div 
                class="relative mr-3% mt-24rpx h-180rpx w-180rpx overflow-hidden rounded-16rpx">
                <image
                  class="absolute left-50% top-50% h-180rpx w-180rpx rounded-16rpx"
                  style="transform: translate(-50%, -50%);" :src="itm.productImage" mode="aspectFill" />
                <div class="absolute left-0 top-0 box-border rounded-0rpx rounded-lt-12rpx rounded-rb-12rpx bg-hex-FF4E4E px-8rpx py-4rpx text-20rpx text-hex-fff">{{ handlegetactive(item.active) }}</div>
              </div>
              
              <div class="w-70% flex flex-col justify-between">
                <div class="text-28rpx font-600 text-hex-333333">{{ itm.productName }}</div>
                <div class="flex items-center text-24rpx text-hex-7C8699">
                  <div>{{ itm.specs }}</div>
                </div>
              </div>
            </div>
            <div class="w-10% flex flex-col justify-between">
              <div>
                <div class="mb-4rpx text-28rpx text-hex-333333">¥{{ itm.promotePrice }}</div>
                <div class="text-24rpx text-hex-999999 line-through">¥{{ itm.price }}</div>
              </div>
              <div class="text-24rpx text-hex-999999">x{{ itm.amount }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="mb-24rpx box-border rounded-24rpx bg-hex-fff p-24rpx">
      <div class="relative mb-36rpx mt-56rpx border-2rpx border-transparent border-b-hex-F5F5F5 border-solid pb-34rpx">
        <div class="mb-56rpx flex justify-between">
          <div class="text-28rpx text-hex-333333">配送费</div>
          <div v-if="orderDetail" class="flex items-center text-24rpx text-hex-333333">
            ¥{{ orderDetail.deliveryAmount }}
          </div>
        </div>
        <div v-if="isCanUseCoupon" class="flex justify-between" @click="navTo(`/pages-mine/selectCoupon?productId=${orderDetail.business}`)">
          <div class="text-28rpx text-hex-333333">优惠</div>
          <div class="flex items-center text-24rpx text-hex-FF5A5A">
            {{ integralStore.couponText }}
            <image
              :src="`${cdnUrl}/svgicons/home/more.svg`"
              mode="scaleToFill"
              class="h-32rpx w-32rpx"
            />
          </div>
        </div>
        <div v-if="!isCanUseCoupon" class="flex justify-between">
          <div class="text-28rpx text-hex-333333">优惠</div>
          <div class="flex items-center text-24rpx text-hex-7C8699">
            暂无可用优惠券
            <image
              :src="`${cdnUrl}/svgicons/home/more.svg${imgVersion}`"
              mode="scaleToFill"
              class="h-32rpx w-32rpx"
            />
          </div>
        </div>
        <div class="absolute h-36rpx w-36rpx rounded-50% bg-hex-F5F5F5 -bottom-18rpx -left-54rpx" />
        <div class="absolute h-36rpx w-36rpx rounded-50% bg-hex-F5F5F5 -bottom-18rpx -right-54rpx" />
      </div>
      <div class="mb-32rpx flex items-center justify-between border-2rpx border-transparent border-b-hex-F5F5F5 border-solid pb-32rpx">
        <div v-if="!isCanUsePoint" class="text-28rpx text-hex-DADADA">积分抵扣</div>
        <div v-if="isCanUsePoint" class="text-28rpx text-hex-333333">积分抵扣</div>
        <div v-if="!isCanUsePoint" class="h-36rpx w-36rpx border-4rpx border-hex-DADADA rounded-50% border-solid" />
        <div v-if="isCanUsePoint" class="h-66rpx w-66rpx flex items-center justify-center">
          <image
            v-if="isSelectUsePoint && integralStore.pointAmount>0" :src="`${cdnUrl}/svgicons/userComment/select.svg${imgVersion}`"
            mode="scaleToFill"
            class="h-44rpx w-44rpx"
            @click="changeIsSelectUsePoint"
          />
          <div v-else class="h-32rpx w-32rpx border-4rpx border-hex-ABCD03 rounded-50% border-solid" @click="changeIsSelectUsePoint" />
        </div>
      </div>
      <div v-if="orderDetail"
           class="text-right text-28rpx text-hex-333333">共{{ orderDetail.totalQuantity }}件商品,小计¥{{ orderDetail.payAmount }}</div>
    </div>
    <div class="box-border flex justify-between rounded-24rpx bg-hex-ffffff p-32rpx text-28rpx text-hex-333333" @click="openNotesDialog">
      <div>备注</div>
      <div class="w-60% truncate">{{ remark }}</div>
      <div>
        <image
          :src="`${cdnUrl}/imgs/tea/more.png${imgVersion}`"
          mode="scaleToFill"
          class="h-32rpx w-32rpx"
        />
      </div>
    </div>
    <div class="h-140rpx" />
    <div class="activeclass fixed bottom-0 left-0 right-0 h-136rpx rounded-t-32rpx bg-hex-ffffff">
      <div class="box-border flex items-center justify-between p-32rpx">
        <div>
          <div
            v-if="orderDetail"
            class="mb-6rpx text-24rpx text-hex-333333">待支付 <text class="font-numberFont text-32rpx text-hex-333333">¥{{ integralStore.finallyPayAmount }}</text></div>
          <div
            v-if="orderDetail"
            class="text-24rpx text-hex-E36043">总计优惠<text>¥{{ integralStore.finallyDiscountAmount }}</text></div>
        </div>
        <div class="btn-theme-bg h-72rpx w-272rpx rounded-46rpx text-center leading-72rpx text-hex-ffffff"
             @click.stop="submitOrder">去支付</div>
      </div>
    </div>
    <!-- 库存不足提示弹窗 -->
    <uni-popup ref="delpop">
      <div class="relative h-600rpx w-548rpx overflow-hidden rounded-30rpx">
        <div class="h-92rpx" />
        <div class="h-480rpx w-548rpx">
          <image class="mt--92rpx h-full w-548rpx" :src="`${cdnUrl}/imgs/detail/deletebg.png${imgVersion}`" mode="scaleToFill" />
          <div class="absolute left-0 right-0 top-20rpx text-center">
            <div class="mt-40% text-36rpx font-bold text-hex-333333">下手慢啦~</div>
            <div class="mb-60rpx mt-10rpx text-36rpx font-bold text-hex-333333">{{ freeList }}已售罄!</div>
            <div class="mb-40rpx flex justify-around rounded-b-30rpx bg-hex-ffffff">
              <div class="mb-40rpx h-68rpx w-182rpx rounded-72rpx bg-hex-ABCD03 text-center text-28rpx leading-68rpx text-hex-ffffff" @click="handleConfirm">去换一个</div>
            </div>
          </div>
        </div>
      </div>
    </uni-popup>
    <!-- 备注弹窗 -->
    <uni-popup ref="notespop" type="bottom" class="z-999">
      <div class="rounded-t-32rpx bg-hex-fff px-32rpx pb-50rpx">
        <div class="h-80rpx w-100% leading-80rpx">
          <div class="relative text-center text-32rpx text-hex-000000">
            订单备注
            <image
              class="absolute right-0 z-99 h-70rpx w-70rpx"
              :src="`${cdnUrl}/imgs/login/cancle.png${imgVersion}`"
              mode="scaleToFill"
              @click="closePop"
            />
          </div>
        </div>
        <div class="">
          <uni-easyinput
            v-model="notesContent"
            class="rounded-18rpx" :inputBorder="false" maxlength="500"
            autoHeight="true" type="textarea"
            placeholderStyle="color:#C4C4C4;font-size:32rpx"
            placeholder="请备注内容"
          />
        </div>
        <div class="text-right text-24rpx text-hex-cccccc">{{ notesContent.length }}/500</div>
        <div class="mt-48rpx flex items-center justify-center">
          <div class="h-92rpx w-100% rounded-46rpx bg-hex-ABCD03 text-center leading-92rpx text-hex-fff"
               @click="confirmInput"
          >确定</div>
        </div>
      </div>
    </uni-popup>
  </div>
</template>

<script lang="ts" setup>
import { useUserStore } from '@/stores/user'
import { useAddressStore } from '@/stores/address'
import { useShopStore } from '@/stores/shop'
import { useIntegralStore } from '@/stores/integral'


let integralStore: any = useIntegralStore()
let shopStore: any = useShopStore()
let addressStores: any = useAddressStore()
let location: any = useAddressStore()
let searchBarTop: any = $ref('24')
const userStores = useUserStore()
let notespop: any = $ref('')
let remark: any = $ref('')
let notesContent: any = $ref('') //备注的内容
let params: any = $ref('')
let isBuyNow: any = $ref()
onLoad((options) => {
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  // #endif
  if (options) {
    isBuyNow = options?.isBuyNow
    if (isBuyNow === '1') {
      params = JSON.parse(decodeURIComponent(options?.params))
    }
  }
})
const goback = () => {
  uni.navigateBack({
    delta: 1,
  })
}

const closePop = () => {
  notespop.close()
}

const confirmInput = () => {
  remark = notesContent
  closePop()
}

let delpop: any = $ref('')

// 回到首页换一个商品
const handleConfirm = () => {
  uni.switchTab({
    url: '/pages/index',
  })
  uni.$emit('shopHandelEvent')
}

let freeList: any = $ref('')
// 获取购物车的数据
const getGoodsList = async () => {
  const reqData = {
    method: 'post',
    data: {
      'storeId': shopStore.shopDefaultStoreId,
      'trolleyType': 3,
    },
    headers: { UserId: userStores.user.id },
  }
  const { data, status, error } = await Fetch('/qqyapi/order/trolley/renderTrolleyViewDto', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }

  if (data.code === 0) {
    let freezeGoodsList: any = []
    freezeGoodsList = data?.result?.freezeItems
    if (freezeGoodsList.length > 0) {
      let tempList: any = []
      let filterList: any = []
      filterList = freezeGoodsList.filter((item) => {
        return item.selectStatus === 0
      })
      filterList.forEach((item) => {
        tempList.push(item.itemName)
      })
      if (tempList.length === 0) {
        return
      }
      if (tempList.length > 3) {
        tempList = tempList.splice(0, 3)
      }
      freeList = tempList.join('、')
      freeList = `${freeList}等`
      delpop.open('center')
    }
  }
}


const goPay = async (bussinessId) => {
  const reqData = {
    method: 'post',
    data: {
      orderBusinessId: bussinessId,
    },
  }
  uni.showLoading({ title: 'Loading...' })
  const { data, status, error } = await Fetch('/qqyapi/payment/checkoutCounter/prepay', reqData)
  if (status === 200 && data.code === 0) {
    let params = data.result
    uni.requestPayment({
      'provider': 'wxpay', // 服务提提供商
      'orderInfo': {},
      'nonceStr': params.nonceStr,
      'package': params.packageVal,
      'signType': params.signType,
      'paySign': params.paySign,
      'timeStamp': params.timeStamp,
      success() {
        uni.showLoading({ title: 'Loading...' })
        setTimeout(() => {
          uni.hideLoading()
          navTo('/pages-shop/paySuccess')
        }, 1000)
      },
      fail() {
        uni.hideLoading()
        navTo('/pages-mine/order?appType=3')
      },
    })
  }
  uni.hideLoading()
}

let orderDetail: any = $ref({})
let goodsList: any = $ref([])
let userInfoDo: any = $ref({})
let orderStoreDo: any = $ref({})
let itemList: any = $ref([])
let totalPayAmount: any = $ref(0)
let payAmount: any = $ref(0)
let finallyDiscountAmount: any = $ref(0)
let discountAmount: any = $ref(0)
let productIdList: any = $ref([])
let realGoodsList: any = $ref([])
const getOrderDetail = async () => {
  productIdList = []
  if (isBuyNow === '0') {
    const reqData = {
      method: 'post',
      data: { 'storeId': shopStore.shopDefaultStoreId },
      headers: {
        AppType: 3,
        UserId: userStores.user.id,
      },
    }
    const { data, status, error } = await Fetch('/qqyapi/order/order/confirmOrder', reqData)
    if (status !== 200 || data.code !== 0) {
      return
    }
    if (data.code === 0) {
      orderDetail = data?.result
      goodsList = orderDetail.cartItemList
      goodsList.forEach(item => productIdList.push(item.productId))
      // topindex = orderDetail.deliveryMethod
      let tempActivrList: any = []
      tempActivrList = goodsList.filter(item => item.cartItemId === null)
      realGoodsList = goodsList.filter(item => item.cartItemId !== null)
      console.log(tempActivrList, 'tempActivrList-----')
      realGoodsList.forEach((item) => {
        tempActivrList.forEach((itm) => {
          if (item.cartItemId === itm?.cartItemExtraInfo?.linkCartItemId) {
            item.childList = []
            item.childList.push(itm)
            item.isHasActive = true
            item.active = itm?.cartItemExtraInfo?.cartItemTypeEnum
            item.activeName = itm?.cartItemExtraInfo?.activityName
          }
        })
        if (!isNilOrEmpty(item.cartItemExtraInfo)) {
          item.isHasActive = true
          item.active = item?.cartItemExtraInfo?.cartItemTypeEnum
          item.activeName = item?.cartItemExtraInfo?.activityName
        }
      })
      console.log(realGoodsList, 'realGoodsList-----')

      payAmount = orderDetail.payAmount
      integralStore.updateInitTotalAmount(payAmount)
      discountAmount = orderDetail.discountAmount
      integralStore.updateInitDiscountAmount(discountAmount)
      userInfoDo = orderDetail.userAddressDo
      orderStoreDo = orderDetail.storeDo
      goodsList.forEach((item) => {
        itemList.push({
          'amount': item.amount,
          'cartItemId': item.cartItemId,
          'childrenSpu': '',
          'itemList': item.cartItemDetailList,
          'price': item.price,
          'productId': item.productId,
          'productImage': item.productImage,
          'productName': item.productName,
          'promotePrice': item.promotePrice,
          'specs': item.specs,
        })
      })
      if (!userInfoDo) {
        userInfoDo = addressStores.selectData
        if (Object.keys(userInfoDo).length === 0) {
          uni.showToast({
            title: '请先添加地址!',
            icon: 'none',
          })
          setTimeout(() => {
            navTo('/pages-shop/deliveryWay?isUpdateAddress=0')
          }, 1800)
        }
      }
      if (!orderStoreDo) {
        orderStoreDo = addressStores.selectStores
      }
      location.updateSelfPickup(1)
    }
  } else {
    const reqData = {
      method: 'post',
      data: {
        'skuDetailDTO': params,
        'storeId': shopStore.shopDefaultStoreId,
        'userAddressId': addressStores?.selectData?.id,
        'userId': userStores.user.id,
      },
      headers: { UserId: userStores.user.id },
    }
    // const { status, data, error } = await Fetch('http://192.168.0.105:8077/order/nowConfirmOrder', reqData)
    const { status, data, error } = await Fetch('/qqyapi/order/order/nowConfirmOrder', reqData)
    if (status !== 200 || data.code !== 0) {
      return
    }
    if (data.code === 0) {
      orderDetail = data?.result
      goodsList = orderDetail.cartItemList
      goodsList.forEach(item => productIdList.push(item.productId))
      // topindex = orderDetail.deliveryMethod
      payAmount = orderDetail.payAmount
      integralStore.updateInitTotalAmount(payAmount)
      discountAmount = orderDetail.discountAmount
      integralStore.updateInitDiscountAmount(discountAmount)
      userInfoDo = orderDetail.userAddressDo
      orderStoreDo = orderDetail.storeDo
      goodsList.forEach((item) => {
        itemList.push({
          'amount': item.amount,
          'cartItemId': item.cartItemId,
          'childrenSpu': '',
          'itemList': item.cartItemDetailList,
          'price': item.price,
          'productId': item.productId,
          'productImage': item.productImage,
          'productName': item.productName,
          'promotePrice': item.promotePrice,
          'specs': item.specs,
        })
      })
      if (!userInfoDo) {
        userInfoDo = addressStores.selectData
        if (Object.keys(userInfoDo).length === 0) {
          uni.showToast({
            title: '请选择收货地址!',
            icon: 'none',
          })
          setTimeout(() => {
            navTo('/pages-shop/deliveryWay?isUpdateAddress=0')
          }, 1800)
        }
      }
      if (!orderStoreDo) {
        orderStoreDo = addressStores.selectStores
      }
      location.updateSelfPickup(1)
      realGoodsList = goodsList
    }
  }
}

let submitBusinessId: any = $ref('') //订单编号
// 购物车过来的提交订单
const carSubmitOrder = async () => {
  let reqData: any = {}
  if (isNilOrEmpty(integralStore.selectCoupon)) {
    reqData = {
      method: 'post',
      data: {
        'businessId': orderDetail.business,
        'deliveryMethod': 0,
        'itemList': itemList,
        'remark': remark,
        'storeId': shopStore.shopDefaultStoreId,
        'trolleyType': 3,
        'userAddressId': userInfoDo?.id,
        'userId': userStores.user.id,
        'usePointsDeduction': isSelectUsePoint,
      },
      headers: {
        AppType: 3,
        UserId: userStores.user.id,
      },
    }
  } else {
    reqData = {
      method: 'post',
      data: {
        'businessId': orderDetail.business,
        'couponAbstractDTO': {
          'beginUseLimitDate': integralStore?.selectCoupon?.beginUseLimitDate,
          'endUseLimitDate': integralStore?.selectCoupon?.endUseLimitDate,
          'templateId': integralStore?.selectCoupon?.templateId,
        },
        'deliveryMethod': 0,
        'itemList': itemList,
        'remark': remark,
        'storeId': shopStore.shopDefaultStoreId,
        'trolleyType': 3,
        'userAddressId': userInfoDo?.id,
        'userId': userStores.user.id,
        'usePointsDeduction': isSelectUsePoint,
      },
      headers: {
        AppType: 3,
        UserId: userStores.user.id,
      },
    }
  }
  uni.showLoading({ title: 'Loading...' })
  // const { status, data, error } = await Fetch('http://192.168.0.105:8066/order/submitOrder', reqData)
  const { status, data, error } = await Fetch('/qqyapi/order/order/submitOrder', reqData)
  if (status !== 200 || data.code !== 0) {
    uni.hideLoading()
    return
  }
  if (data.code === 0) {
    submitBusinessId = data?.result
    goPay(submitBusinessId)
  }
}
// 立即购买的提交订单
const buyBowSubmitOrder = async () => {
  let reqData: any = {}
  if (isNilOrEmpty(integralStore.selectCoupon)) {
    reqData = {
      method: 'post',
      data: {
        'businessId': orderDetail.business,
        'orderRemark': remark,
        'skuDetailDTO': params,
        'storeId': shopStore.shopDefaultStoreId,
        'userAddressId': userInfoDo?.id,
        'userId': userStores.user.id,
        'usePointsDeduction': isSelectUsePoint,
      },
      headers: { AppType: 3, UserId: userStores.user.id },
    }
  } else {
    reqData = {
      method: 'post',
      data: {
        'businessId': orderDetail.business,
        'couponAbstractDTO': {
          'beginUseLimitDate': integralStore?.selectCoupon?.beginUseLimitDate,
          'endUseLimitDate': integralStore?.selectCoupon?.endUseLimitDate,
          'templateId': integralStore?.selectCoupon?.templateId,
        },
        'orderRemark': remark,
        'skuDetailDTO': params,
        'storeId': shopStore.shopDefaultStoreId,
        'userAddressId': userInfoDo?.id,
        'userId': userStores.user.id,
        'usePointsDeduction': isSelectUsePoint,
      },
      headers: { AppType: 3, UserId: userStores.user.id },
    }
  }
  uni.showLoading({ title: 'Loading...' })
  // const { status, data, error } = await Fetch('http://192.168.0.105:8066/order/nowSubmitOrder', reqData)
  const { status, data, error } = await Fetch('/qqyapi/order/order/nowSubmitOrder', reqData)
  if (status !== 200 || data.code !== 0) {
    uni.hideLoading()
    return
  }
  if (data.code === 0) {
    submitBusinessId = data?.result
    goPay(submitBusinessId)
  }
}
// 提交订单
const submitOrder = async () => {
  if (isBuyNow === '0') {
    carSubmitOrder()
  } else {
    buyBowSubmitOrder()
  }
}

const openNotesDialog = () => {
  notespop.open('bottom')
}

// 查看是否有积分可用
let isCanUsePoint: any = $ref(false)
let deductionAmount: any = $ref()
let pointsDeducted: any = $ref()
const getCanUsePoint = async () => {
  let params: any = {}
  params.payAmount = (Number(orderDetail?.payAmount) - Number(orderDetail?.deliveryAmount)).toFixed(2)
  params.orderItemList = orderDetail.cartItemList.map(e => {
    return { productId: e.productId, subAmount: e.subTotal }
  })
  const reqData = {
    method: 'post',
    data: params,
  }
  const { status, data, error } = await Fetch('/qqyapi/member/points/deductionResult', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    let tempObj: any = {}
    tempObj = data?.result
    if (Number(tempObj.deductionAmount) > 0) {
      isCanUsePoint = true
    }
    deductionAmount = tempObj?.deductionAmount
    pointsDeducted = tempObj?.pointsDeducted
  }
}
let isSelectUsePoint: any = $ref(false)
const changeIsSelectUsePoint = () => {
  isSelectUsePoint = !isSelectUsePoint
  if (isSelectUsePoint) {
    integralStore.updatePointAmount(deductionAmount)
  } else {
    integralStore.updatePointAmount(0)
  }
}

// 查看是否有可用优惠券
let isCanUseCoupon: any = $ref(false)
let couponList: any = $ref([])
const getCouponList = async () => {
  let reqData = {
    method: 'post',
    data: {
      'couponAppType': 1,
      'orderPaymentPrice': (Number(orderDetail?.payAmount) - Number(orderDetail?.deliveryAmount)).toFixed(2),
      'productIdList': productIdList,
    },
    headers: { UserId: userStores.user.id },
  }
  const { status, data, error } = await Fetch('/qqyapi/coupon/couponCenter/queryAvailableUseCouponGroupList', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    couponList = data.result
    integralStore.updateCouponList(couponList)
    let couponNum: any = 0
    couponNum = couponList.reduce((sum, item) => sum + item.totalAmount, 0)
    integralStore.updateCouponText(`${couponNum}张可用`)
    if (couponList.length === 0) {
      isCanUseCoupon = false
    } else {
      isCanUseCoupon = true
    }
  }
}

//
const handlegetactive = (act) => {
  switch (act) {
    case 'BUY_GIFTS':
      return '买赠'
      break
    case 'MULTIPLE_DISCOUNT':
      return '多件优惠'
      break
    case 'MARKUP_PURCHASE':
      return '加购'
      break
    case 'FULL_DISCOUNT':
      return '满折'
      break
    case 'FULL_DEDUCTION':
      return '满减'
      break

    default:
      break
  }
}
onMounted(async () => {
  await addressStores.getListData(userStores.user.id, 1, 10) //默认先获取10条，用来方便处理没有默认地址取第一条
  await addressStores.defaultaddress(userStores.user.id)
  await integralStore.handleInitBlank()
  await getOrderDetail()
  await getCanUsePoint()
  await getCouponList()
  // await getActive()
})
watchEffect(() => {
  uni.$on('shopWakeEvent', () => {
    getGoodsList()
    getOrderDetail()
  })
  uni.$on('shopUpdateAddress', async (item) => {
    userInfoDo = item
  })
})
</script>

<style lang="scss" scoped>
.comfirmOrder{
  .activeclass{
    box-shadow: 0rpx -2rpx 8rpx 0rpx rgb(0 0 0 / 6%);
  }

  .font-numberFont{
    font-family:'DingTalk JinBuTi';
  }

  ::v-deep(.uni-easyinput){
    .uni-easyinput__content{
      background-color: #f5f5f5 !important;
      border-radius: 18rpx;
      padding: 15rpx;
      box-sizing: border-box;
    }
  }
}
</style>
